package com.engine4cloud.tdf.supervision.component;

import com.engine4cloud.tdf.common.core.callback.CallBackExecute;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.io.IOException;

/**
 * 电子围栏监听器
 */
@Component
public class CallBackComponent {

    public void execute(final CallBackExecute action) {

        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager
                    .registerSynchronization(new TransactionSynchronization() {
                        @Override
                        public void afterCommit() {
                            // 事务提交后执行回调
                            try {
                                action.callback();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
        } else {
            // 事务提交后执行回调
            try {
                action.callback();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
